import React, { useRef } from 'react';
import { View, TouchableNativeFeedback, Alert } from 'react-native'
import ViewShot from "react-native-view-shot";
import QRCode from 'react-native-qrcode-svg';
import { SaveImg } from '@/app/utils/selectImg'
import { size } from '@/app/utils';

interface QRCodeScreenProps {
    value: string;
    size?: number;
}

const QRCodeScreen: React.FC<QRCodeScreenProps> = (props) => {
    const saveQRCode = useRef<any>(null);

    const onSaveQRCode = async () => {
        if (saveQRCode.current) {
            try {
                const url = await saveQRCode.current.capture();
                const success = await SaveImg(url);
                if (success) {
                    Alert.alert('成功', '二维码已保存到相册');
                }
            } catch (error) {
                console.error('保存二维码失败:', error);
                Alert.alert('失败', '保存二维码失败，请检查相册权限');
            }
        } else {
            Alert.alert('错误', '二维码组件未准备就绪');
        }
    }

    return (
        <ViewShot ref={saveQRCode} options={{ fileName: "Your-File-Name", format: "png", quality: 1 }} style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <TouchableNativeFeedback onLongPress={() => onSaveQRCode()}>
                <View style={{ padding: size(20), backgroundColor: '#fff', borderRadius: size(4) }}>
                    <QRCode
                        value={props.value}
                        size={props.size || size(200)}
                    />
                </View>
            </TouchableNativeFeedback>
        </ViewShot>
    )
}

export default QRCodeScreen;